import pdfplumber
from flask import request
from flask_cors import *
from loguru import logger
import re
import os
from json_flask import JsonFlask
from json_response import JsonResponse
import traceback

server = JsonFlask(__name__)
CORS(server, supports_credentials=True)


@server.errorhandler(Exception)
def all_exception_handler(error):
    """
        全局异常捕获，也相当于一个视图函数，全局异常处理
    """
    traceback.print_exc()
    return JsonResponse.error(msg=str(error))


@server.route('/uploadFile', methods=['post'])
def upload_file():
    """
    上传文件，参数类型为文件类型
    """
    bill_list = []
    try:
        current_path = os.path.dirname(__file__)
        # 文件路径
        upload_path = os.path.join(current_path, 'upload')
        if not os.path.exists(upload_path):
            os.makedirs(upload_path)
        # 文件
        file = request.files['file']
        file_path = os.path.join(upload_path, file.filename)
        logger.info("文件路径：{}".format(file_path))
        # 保存文件
        file.save(file_path)
        # 读取文件
        with pdfplumber.open(file_path) as pdf:
            page01 = pdf.pages[0]  # 指定页码
            text = page01.extract_text()  # 提取文本
            # 先按照【Debits Credits Debits Credits】切割
            text = text.split("Debits Credits Debits Credits")[-1]
            # 按照换行符切割text
            text_list = text.split("\n")
            for text in text_list:
                if len(text.strip()) == 0:
                    continue
                # 替换逗号
                if "Debits" in text:
                    text = text.replace("Debits", "")
                if "Credits" in text:
                    text = text.replace("Credits", "")
                text = text.replace(",", "")
                text = text.strip()
                if text.startswith("subtotals"):
                    continue
                if text.startswith("Tax"):
                    continue
                if text.startswith("Information"):
                    continue
                # 金额的正则表达式
                amounts = re.findall(r'(([-+])?\d+(\.\d+)?)', text)
                if len(amounts) == 0:
                    continue
                size = len(amounts)
                if size == 1:
                    amount = amounts[0][0]
                    bill_text = text.replace(amount, "").strip()
                    if bill_text == "Transfers" or bill_text == "Tax":
                        continue
                    bill_list.append({"billName": bill_text, "amount": amount})
                    continue
                amount_list = []
                for i in range(size):
                    amount_list.append(amounts[i][0])
                split_text = "|".join(amount_list)
                # 按照多个金额切割
                text_list = re.split(split_text, text)
                # 通过索引取值
                for i in range(size):
                    bill_text = text_list[i].strip()
                    if bill_text == "Transfers" or bill_text == "Tax":
                        continue
                    bill_list.append({"billName": bill_text, "amount": amount_list[i]})
        return JsonResponse.success(data=bill_list)
    except Exception as e:
        logger.error(e)
        return JsonResponse.error(msg=str(e))


server.run(port=8888, debug=True, host='0.0.0.0')
